package com.ld.security.common.core.base.column;


import com.ld.security.common.core.util.StringUtil;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class MapJson extends HashMap implements  SuperColumn {


    /**
     * 类型转换器
     * @param clazz
     * @param <E>
     * @return
     */
    public <E> E mapToObject(Class<E> clazz){
        MyInvokationHandler invokationHandler = new MyInvokationHandler(this);

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);

        enhancer.setCallback(invokationHandler);

        E result = (E) enhancer.create();
        return  result;

    }

    public static class MyInvokationHandler implements MethodInterceptor
    {

        Map data;

        public MyInvokationHandler(Map data) {
            this.data = data;
        }


        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

            String name = method.getName();
            if(name.contains("get")){
                name = name.substring(3);
            }else if(name.contains("is")){
                name=name.substring(2);
            }
            name =  StringUtil.toLowerCaseFirstOne(name);

            Object val = data.get(name);


            return val;
        }
    }


}
